package com.wyp168.es.service.Impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.TotalHits;
import co.elastic.clients.elasticsearch.core.search.TotalHitsRelation;
import com.wyp168.es.service.ESService;
import com.wyp168.es.vo.BankVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @ClassName ESServiceImpl
 * @Title TODO
 * @Description TODO
 * @Author wyp168
 * @Date 2023/8/12 14:30
 */
@Service
@Slf4j
public class ESServiceImpl implements ESService {

    @Autowired
    private ElasticsearchClient esClient;

    public static final String INDEX = "bank";

    @Override
    public void list() {
        try {
            String searchText = "Amber";
            SearchResponse<BankVO> response = esClient.search(s -> s
                            .index(INDEX)
                            .query(q -> q
                                    .match(t -> t
                                            .field("firstname")
                                            .query(searchText)
                                    )
                            ),
                    BankVO.class
            );
            TotalHits total = response.hits().total();
            boolean isExactResult = total.relation() == TotalHitsRelation.Eq;

            if (isExactResult) {
                log.info("There are " + total.value() + " results");
            } else {
                log.info("There are more than " + total.value() + " results");
            }

            List<Hit<BankVO>> hits = response.hits().hits();
            for (Hit<BankVO> hit: hits) {
                BankVO product = hit.source();
                log.info("Found Firstname " + product.getFirstname() + ", score " + hit.score());
            }
        } catch (IOException e) {
            log.error("检索失败");
            throw new RuntimeException("es检索失败");
        }
    }
}
